/**
 * 友链 blogroll
 */
const express = require("express");
const { body, query } = require("express-validator");
const router = express.Router();
const {
  selectBlogrollList,
  insertBlogroll,
  updateBlogroll,
  deleteBlogroll,
} = require("@root/services/blog/blogroll.service.js");

// 参数校验统一封装
const { currentPage, pageSize, id, site_name, site_url, site_icon, description } = {
  currentPage: ([prop = "currentPage", validator = query] = []) =>
    validator(prop)
      .notEmpty()
      .withMessage("currentPage不能为空")
      .isNumeric({
        no_symbols: true,
      })
      .withMessage("currentPage必须是正整数"),
  pageSize: ([prop = "pageSize", validator = query] = []) =>
    validator(prop)
      .notEmpty()
      .withMessage("pageSize不能为空")
      .isNumeric({ no_symbols: true })
      .withMessage("pageSize必须是正整数"),
  id: ([prop = "id", validator = body] = []) =>
    validator(prop)
      .notEmpty()
      .withMessage("id不能为空")
      .isNumeric({ no_symbols: true })
      .withMessage("id必须是正整数"),
  site_name: ([prop = "site_name", validator = body] = []) =>
    validator(prop).notEmpty().withMessage("site_name不能为空"),
  site_url: ([prop = "site_url", validator = body] = []) =>
    validator(prop).isURL().withMessage("site_url必须是有效的链接"),
  site_icon: ([prop = "site_icon", validator = body] = []) =>
    validator(prop)
      .notEmpty()
      .withMessage("site_icon不能为空")
      .isURL()
      .withMessage("网站图标必须是有效的链接"),
  // .matches(/\.(jpeg|jpg|gif|png)$/i)
  // .withMessage("网站图标必须是图片链接"),
  email: ([prop = "email", validator = body] = []) =>
    validator(prop).isEmail().withMessage("email必须是有效的邮箱"),
  description: ([prop = "description", validator = body] = []) =>
    validator(prop).notEmpty().withMessage("描述不能为空"),
};

/**
 * 获取友链
 */
router.get("/", [currentPage(), pageSize()], selectBlogrollList);

/**
 * 新增友链
 */
router.post("/", [site_name(), site_url(), description()], insertBlogroll);

/**
 * 修改友链
 */
router.put("/", [id(), site_name(), site_url(), site_icon(), description()], updateBlogroll);

/**
 * 删除友链
 */
router.delete(
  "/",
  [
    body("ids").isArray({ min: 1 }).withMessage("ids必须是数组,且不能为空"),
    body("ids.*").isInt({ min: 1 }).withMessage("数组中的元素必须是正整数"),
  ],
  deleteBlogroll
);

module.exports = router;
